package movee.service;

import movee.auth.AppAuthService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author movee
 */
@Service
@Slf4j
public class WebHintService {

    private static final long MAX_SIZE = 1024;
    private static final long EXPIRE_AFTER_WRITE_MINUTE = 10;

    private final AppAuthService authService;

    private final Gson gson;
    private final Cache<String, String> cache;
    private final Type stringListType;

    @Autowired
    public WebHintService(AppAuthService authService) {
        this.authService = authService;

        gson = new GsonBuilder().create();
        cache = Caffeine.newBuilder()
                .maximumSize(MAX_SIZE)
                .expireAfterWrite(EXPIRE_AFTER_WRITE_MINUTE, TimeUnit.MINUTES)
                .softValues()
                .build();

        stringListType = new TypeToken<List<String>>() { }.getType();
    }

    private List<String> getHintDataList(List<String> origins, String cacheKey) {
        if (CollectionUtils.isEmpty(origins)) {
            // 尝试从缓存获取
            String cached = cache.get(cacheKey, k -> gson.toJson(new ArrayList<String>()));
            return StringUtils.isEmpty(cached) ? new ArrayList<>() : gson.fromJson(cached, stringListType);
        } else {
            // 缓存
            cache.put(cacheKey, gson.toJson(origins));
            return origins;
        }
    }

    /**
     * 解析cookie，获取用户名
     * @param cookie cookie
     * @return 用户名
     */
    public String getCookieUser(final String cookie) {
        return authService.getUser(cookie);
    }
}
